package com.yanqu.road.server.task;

import com.yanqu.road.server.command.CommandControl;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.queue.ICommandQueue;
import com.yanqu.road.server.command.Command;
import io.netty.channel.ChannelHandlerContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class GameCommandTask implements Runnable {
	private static Logger logger = LogManager.getLogger(GameCommandTask.class.getName());
	private static Logger commandLogger = LogManager.getLogger("COMMAND_TIME");
	private ChannelHandlerContext ctx;

	private YanQuMessage yanQuMessage;
	private long receiveTime;
	private ICommandQueue player;

	public GameCommandTask(ChannelHandlerContext ctx, YanQuMessage yanQuMessage, ICommandQueue player) {
		this.ctx = ctx;
		this.yanQuMessage = yanQuMessage;
		this.player = player;
		this.receiveTime = System.currentTimeMillis();
	}

	@Override
	public final void run() {
		long beginTime = System.currentTimeMillis();
		Command cmd = null;
		try {
			cmd = CommandControl.getCommand(yanQuMessage.getCode());
			if (cmd != null) {
				cmd.execute(ctx, yanQuMessage);
			}
		} catch (Exception e) {
			logger.error("执行Command错误 ,message : {}" , yanQuMessage, e);
		} finally {
			if (player != null) {
				player.getCommandQueue().remove();
			}
		}
		long now = System.currentTimeMillis();
		long costTime = now - receiveTime;
		long executeTime = now - beginTime;
		if (costTime >= 21) {
			String className = "";
			if (cmd != null) {
				className = cmd.getClass().getSimpleName();
			}
			commandLogger.debug("总消耗时长:{} Millis,执行时间:{} Mills, userId:{}, code:{} className:{}  ", costTime,executeTime,
					yanQuMessage.getPlayerId(), yanQuMessage.getCode(), className);
		}
	}
}
